# -*- coding：utf-8 -*-
import uuid
import time
from api.api import Api
from utils.config import PARAMETER_WRITE_TEMPLATE
from utils.data_convert import DataConverter
from utils.log_util import logger


def gly_write(result, app_id, entry_id, batch_size=100, max_retries=3):
    """优化后的批量写入函数"""
    if not result:
        logger.debug("数据库查询无数据，跳过写入操作")
        return 200
    json_data = {
        **PARAMETER_WRITE_TEMPLATE,
        'app_id': app_id,
        'entry_id': entry_id
    }
    total_items = len(result)
    logger.debug(f"开始写入 | 表单ID: {entry_id} | 总数据量: {total_items}条")
    batch_send = 0
    total_batches = (total_items + batch_size - 1) // batch_size
    for batch_index in range(0, total_items, batch_size):
        batch = result[batch_index:batch_index + batch_size]
        transaction_id = str(uuid.uuid4())
        try:
            converted_batch = [DataConverter.convert_item(item) for item in batch]
        except Exception as e:
            logger.error(f"表单ID {entry_id} | 批次 {batch_index // batch_size + 1} 数据转换失败: {str(e)}")
            return 500
        json_data.update({
            'transaction_id': transaction_id,
            'data_list': converted_batch
        })
        for attempt in range(max_retries + 1):
            try:
                api_response = Api().write(json_data)
                if api_response.status_code != 200:
                    raise ValueError(f"状态码: {api_response.status_code}")
                response_json = api_response.json()
                success_count = response_json.get('success_count', 0)
                batch_send += success_count
                logger.debug(
                    f"批次 {batch_index // batch_size + 1}/{total_batches}  | 累计写入: {success_count}/{batch_send}"
                )
                break

            except Exception as e:
                if attempt >= max_retries:
                    logger.error(f"表单ID {entry_id} | 批次 {batch_index // batch_size + 1} 达到最大重试次数: {str(e)}")
                    return 500
                time.sleep(2 ** attempt)

    logger.info(f"写入完成 | 表单ID: {entry_id} | 写入数量:{batch_send} | 总数据量:{total_items}")
    return 200